import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:wms/utils/message_box.dart';
import 'package:wms/utils/utils.dart';
import '../system/fontsize_provider.dart';
import '../../utils/rangeInput_formatter.dart';
import '../../services/auth_service.dart';
import '../../services/api_service.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class MoveStockScreen extends StatefulWidget {
  const MoveStockScreen({super.key});

  @override
  State<MoveStockScreen> createState() => _MoveStockScreenState();
}

class _MoveStockScreenState extends State<MoveStockScreen> with WidgetsBindingObserver {
  // 输入控制器
  final TextEditingController _itemController = TextEditingController();
  final TextEditingController _locationController = TextEditingController();
  final TextEditingController _quantityController = TextEditingController();
  final TextEditingController _destLocController = TextEditingController();
  final TextEditingController _notesController = TextEditingController();

  // 焦点控制器
  final FocusNode _itemFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _locationFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _quantityFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _destLocFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _notesFocusNode = FocusNode(canRequestFocus: true);

  // 键盘状态管理（默认全部收起）
  bool _locationKeyboardVisible = false;
  bool _itemKeyboardVisible = false;
  bool _quantityKeyboardVisible = false;
  bool _destLocKeyboardVisible = false;
  String? _currentFocusField;

  // 业务数据
  int? currentQuantity;
  late int maxAllowedValue = 99999999;
  late double _fontScale;
  int? warehouseId;
  String? location;
  String? packKey;
  String? itemNumber;
  String? internalItemNumber;
  Map<String, String?> validationErrors = {};
  static const double _bottomButtonHeight = 80;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    
    // 输入监听
    _itemController.addListener(() => _clearErrorOnInput('item'));
    _locationController.addListener(() => _clearErrorOnInput('location'));
    _quantityController.addListener(() => _clearErrorOnInput('move quantity'));
    _destLocController.addListener(() => _clearErrorOnInput('dest loc'));
    
    // 焦点监听
    _initFocusListeners();
    
    // 初始聚焦Location，先隐藏键盘再聚焦
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (mounted) {
        await _hideKeyboard();
        _focusOnField('location', showKeyboard: false);
      }
    });
  }

  // 初始化焦点监听
  void _initFocusListeners() {
    _locationFocusNode.addListener(() {
      _handleFocusChange('location', _locationFocusNode);
      if (_locationFocusNode.hasFocus && !_locationKeyboardVisible) {
        _hideKeyboard();
      }
    });
    _itemFocusNode.addListener(() {
      _handleFocusChange('item', _itemFocusNode);
      if (_itemFocusNode.hasFocus && !_itemKeyboardVisible) {
        _hideKeyboard();
      }
    });
    _quantityFocusNode.addListener(() {
      _handleFocusChange('quantity', _quantityFocusNode);
      if (_quantityFocusNode.hasFocus && !_quantityKeyboardVisible) {
        _hideKeyboard();
      }
    });
    _destLocFocusNode.addListener(() {
      _handleFocusChange('destLoc', _destLocFocusNode);
      if (_destLocFocusNode.hasFocus && !_destLocKeyboardVisible) {
        _hideKeyboard();
      }
    });
  }

  // 应用生命周期监听
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      _resetAllKeyboards();
    }
  }

  // 焦点变化处理
  void _handleFocusChange(String field, FocusNode node) {
    if (node.hasFocus) {
      if (_currentFocusField != null && _currentFocusField != field) {
        _hideKeyboardForField(_currentFocusField!);
      }
      _setCurrentFocusField(field);
    } else if (_currentFocusField == field) {
      // 失去焦点时隐藏当前键盘并更新图标
      _hideKeyboardForField(field);
      _currentFocusField = null;
    }
  }

  // 键盘控制方法
  void _setCurrentFocusField(String field) => setState(() => _currentFocusField = field);
  
  void _showKeyboard() async => await SystemChannels.textInput.invokeMethod('TextInput.show');
  
  Future<void> _hideKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
      await Future.delayed(const Duration(milliseconds: 50));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    } catch (e) {
      print('隐藏键盘失败: $e');
      await Future.delayed(const Duration(milliseconds: 100));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    }
  }
  
  void _showKeyboardForField(String field) => setState(() {
    _updateKeyboardState(field, true);
    _showKeyboard();
  });
  
  void _hideKeyboardForField(String field) => setState(() {
    _updateKeyboardState(field, false);
    _hideKeyboard();
  });
  
  void _toggleKeyboardForField(String field) {
    if (_getKeyboardState(field)) {
      _hideKeyboardForField(field);
      _unfocusField(field);
    } else {
      _focusOnField(field, showKeyboard: true);
    }
  }
  
  // 聚焦方法（主方法）
  void _focusOnField(String field, {required bool showKeyboard}) {
    FocusScope.of(context).unfocus();
    if (mounted) {
      switch (field) {
        case 'location':
          FocusScope.of(context).requestFocus(_locationFocusNode);
          break;
        case 'item':
          FocusScope.of(context).requestFocus(_itemFocusNode);
          break;
        case 'quantity':
          FocusScope.of(context).requestFocus(_quantityFocusNode);
          break;
        case 'destLoc':
          FocusScope.of(context).requestFocus(_destLocFocusNode);
          break;
      }
      if (showKeyboard) {
        _showKeyboardForField(field);
      } else {
        _hideKeyboard();
        // 关键修复：确保聚焦但不显示键盘时，图标状态正确
        _updateKeyboardState(field, false);
      }
    }
  }
  
  // 取消指定输入框焦点
  void _unfocusField(String field) {
    switch (field) {
      case 'location': _locationFocusNode.unfocus(); break;
      case 'item': _itemFocusNode.unfocus(); break;
      case 'quantity': _quantityFocusNode.unfocus(); break;
      case 'destLoc': _destLocFocusNode.unfocus(); break;
    }
  }
  
  // 获取键盘状态
  bool _getKeyboardState(String field) {
    switch (field) {
      case 'location': return _locationKeyboardVisible;
      case 'item': return _itemKeyboardVisible;
      case 'quantity': return _quantityKeyboardVisible;
      case 'destLoc': return _destLocKeyboardVisible;
      default: return false;
    }
  }
  
  // 更新键盘状态
  void _updateKeyboardState(String field, bool visible) {
    setState(() {
      switch (field) {
        case 'location': _locationKeyboardVisible = visible; break;
        case 'item': _itemKeyboardVisible = visible; break;
        case 'quantity': _quantityKeyboardVisible = visible; break;
        case 'destLoc': _destLocKeyboardVisible = visible; break;
      }
    });
  }
  
  // 重置所有键盘状态
  void _resetAllKeyboards() {
    if (_currentFocusField == null && !_locationKeyboardVisible && 
        !_itemKeyboardVisible && !_quantityKeyboardVisible && !_destLocKeyboardVisible) {
      return;
    }
    setState(() {
      _locationKeyboardVisible = false;
      _itemKeyboardVisible = false;
      _quantityKeyboardVisible = false;
      _destLocKeyboardVisible = false;
      _currentFocusField = null;
    });
    FocusScope.of(context).unfocus();
    _hideKeyboard();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _locationFocusNode.removeListener(() => _handleFocusChange('location', _locationFocusNode));
    _itemFocusNode.removeListener(() => _handleFocusChange('item', _itemFocusNode));
    _quantityFocusNode.removeListener(() => _handleFocusChange('quantity', _quantityFocusNode));
    _destLocFocusNode.removeListener(() => _handleFocusChange('destLoc', _destLocFocusNode));
    
    _itemController.dispose();
    _locationController.dispose();
    _quantityController.dispose();
    _notesController.dispose();
    _destLocController.dispose();
    
    _itemFocusNode.dispose();
    _locationFocusNode.dispose();
    _quantityFocusNode.dispose();
    _destLocFocusNode.dispose();
    _notesFocusNode.dispose();
    
    super.dispose();
  }

  // 扫描Location处理
  void _handleLocationBarcode(String value){
    try{
      if(value.isNotEmpty){
        location = value;
        if(value.contains(':')){
          location = Utils.parseQRCode(value, 'location');
          setState(() => _locationController.text = location!);
        }
        if(_itemController.text.isNotEmpty && packKey != null) getQuantity();
        _focusOnField('item', showKeyboard: false);
      }
    } catch(e) {
      MessageBox.showMessageBox(context, e.toString(), isError: true);
    }
  }

  // 扫描Item处理
  void _handleItemBarcode(String value){
    try{
      if(value.contains(':')){
        packKey = Utils.parseQRCode(value,'pack key');
        itemNumber = Utils.parseQRCode(value,'item number');
        internalItemNumber = Utils.parseQRCode(value,'product code');
        setState(() {
          _itemController.text = itemNumber ?? '';
          _quantityController.clear();
        });
        if(_locationController.text.isNotEmpty) getQuantity();
        _focusOnField('quantity', showKeyboard: false);
      }
      if(!value.contains(':') && packKey == null){
        MessageBox.showMessageBox(context, 'Please scan item barcode again.', isError: true);
      }
    } catch(e) {
      MessageBox.showMessageBox(context, e.toString(), isError: true);
    }
  }

  // 获取数量
  Future<void> getQuantity() async{
    if (warehouseId == null) {
      throw Exception('Warehouse ID is missing');
    }
    final warehouseIdParam = 'warehouse=$warehouseId';
    final locationParam = '&location=${_locationController.text.trim()}';
    final packKeyParam = '&pack_key=$packKey';
    final internalItemNumberParam = '&&internal_item_number=$internalItemNumber';
    final apiUrl = '${ApiService.baseURL}${ApiService.fetchMoveQuanyity}$warehouseIdParam$locationParam$packKeyParam$internalItemNumberParam';
    
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    try {
      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
      );
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        if(jsonData['code'] == 2000 && jsonData['data'] != null){
          setState(() {
            currentQuantity = jsonData['data']['quantity'] ?? 0;
            maxAllowedValue = currentQuantity ?? 0;
          });
        } else if (jsonData['code'] == 401) {
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('Session expired, please login again');
        } else {
          setState(() => currentQuantity = null);
          throw Exception(jsonData['msg'] ?? 'Failed to get quantity');
        }
      } else {
        throw Exception('Server error: ${response.statusCode}');
      }
    } catch (e) {
      MessageBox.showMessageBox(context, e.toString(), isError: true);
    }
  }

  // 错误处理
  void _clearErrorOnInput(String fieldKey) {
    if (validationErrors.containsKey(fieldKey)) {
      setState(() {
        if ((fieldKey == 'item' && _itemController.text.isNotEmpty) ||
            (fieldKey == 'location' && _locationController.text.isNotEmpty) ||
            (fieldKey == 'dest loc' && _destLocController.text.isNotEmpty) ||
            (fieldKey == 'move quantity' && _quantityController.text.isNotEmpty)) {
          validationErrors.remove(fieldKey);
        }
      });
    }
  }

  // 提交表单
  void _submitForm() async{
    _resetAllKeyboards();
    bool isValid = true;
    Map<String, String?> errors = {};
    
    try{
      if (_itemController.text.isEmpty) {
        errors['item'] = 'Please input item number.';
        isValid = false;
      }
      if (_locationController.text.isEmpty) {
        errors['location'] = 'Please input location.';
        isValid = false;
      }
      if (_quantityController.text.isEmpty) {
        errors['move quantity'] = 'Please input move quantity.';
        isValid = false;
      }
      if (_destLocController.text.isEmpty) {
        errors['dest loc'] = 'Please input dest loc.';
        isValid = false;
      }

      setState(() => validationErrors = errors);

      if (isValid) {
        final responseData = await _callAdjustmentAPI();
        if(responseData['code'] == 2000){
          setState(() {
            packKey = null;
            internalItemNumber = null;
            _locationController.clear();
            _itemController.clear();
            _destLocController.clear();
            _notesController.clear();
            _quantityController.clear();
            currentQuantity = null;
          });
          _notesFocusNode.unfocus();
          FocusScope.of(context).unfocus();
          await _hideKeyboard();
          MessageBox.showMessageBox(context, responseData['msg']);
          Future.delayed(const Duration(milliseconds: 100), () {
            if (mounted) _focusOnField('location', showKeyboard: false);
          });
        }
      }
    } catch(e) {
      MessageBox.showMessageBox(context, e.toString(), isError: true);
    }
  }

  // 调用API
  Future<Map<String,dynamic>> _callAdjustmentAPI() async{
    final apiUrl = ApiService.baseURL + ApiService.moveLocation;
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    try {
      var requestBody = {
        'warehouse': warehouseId,
        'source_location': _locationController.text.trim(),
        'internal_item_number': internalItemNumber?.trim(),
        'pack_key': packKey?.trim(),
        'move_quantity': _quantityController.text.trim(),
        'dest_location': _destLocController.text.trim(),
        'notes': _notesController.text.trim(),
      };
      
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
        body: jsonEncode(requestBody),
      );
      
      if(response.statusCode == 200){
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        if (jsonData['code'] == 2000) {
          return jsonData;
        } else if(jsonData['code'] == 401){
          AuthService auth = AuthService();
          auth.logout(context);
          throw Exception('Session expired, please login again');
        } else {
          throw Exception(jsonData['msg'] ?? 'Operation failed');
        }
      } else {
        throw Exception('Server error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception(e.toString());
    }
  }

  // 构建输入框行
  Widget _buildLabelInputRow({
    required String label,
    required bool isRequired,
    required String errorKey,
    String? fieldType,
    Widget? suffixWidget,
  }) {
    final isSmallScreen = MediaQuery.of(context).size.width < 360;
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(
          height: 30,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(
                width: 120,
                child: Row(
                  children: [
                    Text(
                      label,
                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13 * _fontScale),
                    ),
                    if (isRequired)
                      const Text('*', style: TextStyle(color: Colors.red)),
                  ],
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: _buildInputField(fieldType, isSmallScreen),
              ),
              if (suffixWidget != null)
                Padding(
                  padding: const EdgeInsets.only(left: 8),
                  child: suffixWidget,
                ),
            ],
          ),
        ),
        if (errorKey != null && validationErrors[errorKey] != null)
          Padding(
            padding: const EdgeInsets.only(left: 136, top: 4),
            child: Text(
              validationErrors[errorKey]!,
              style: TextStyle(color: Colors.red, fontSize: 12 * _fontScale),
            ),
          ),
      ],
    );
  }

  // 输入框组件
  Widget _buildInputField(String? fieldType, bool isSmallScreen) {
    if (fieldType == null) return Container();
    
    TextEditingController? controller;
    FocusNode? focusNode;
    TextInputType keyboardType = TextInputType.text;
    List<TextInputFormatter>? inputFormatters;
    Function(String)? onSubmitted;
    Function()? onTap;
    Function(String)? onChanged;

    switch (fieldType) {
      case 'location':
        controller = _locationController;
        focusNode = _locationFocusNode;
        onSubmitted = _handleLocationBarcode;
        onTap = () => _onInputTap(controller!, fieldType);
        onChanged = (v) {
          _clearErrorOnInput('location');
          if (v.isEmpty) setState(() => currentQuantity = null);
        };
        break;
      case 'item':
        controller = _itemController;
        focusNode = _itemFocusNode;
        onSubmitted = _handleItemBarcode;
        onTap = () => _onInputTap(controller!, fieldType);
        onChanged = (v) {
          _clearErrorOnInput('item');
          if (v.isEmpty) setState(() => _quantityController.clear());
        };
        break;
      case 'quantity':
        controller = _quantityController;
        focusNode = _quantityFocusNode;
        keyboardType = TextInputType.number;
        inputFormatters = [
          FilteringTextInputFormatter.digitsOnly,
          RangeInputFormatter(maxAllowedValue)
        ];
        onSubmitted = (_) => _focusOnFieldWithNotes('destLoc', showKeyboard: false);
        onTap = () => _onInputTap(controller!, fieldType);
        onChanged = (_) => _clearErrorOnInput('move quantity');
        break;
      case 'destLoc':
        controller = _destLocController;
        focusNode = _destLocFocusNode;
        onSubmitted = (_) => _focusOnFieldWithNotes('notes', showKeyboard: false);
        onTap = () => _onInputTap(controller!, fieldType);
        onChanged = (_) => _clearErrorOnInput('dest loc');
        break;
    }

    return TextField(
      controller: controller,
      focusNode: focusNode,
      keyboardType: keyboardType,
      inputFormatters: inputFormatters,
      decoration: InputDecoration(
        border: const OutlineInputBorder(),
        contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 10),
        suffixIcon: IconButton(
          icon: Icon(
            // 关键修复：根据实际键盘状态显示正确图标
            _getKeyboardState(fieldType) ? Icons.keyboard_hide : Icons.keyboard,
            color: const Color(0xFF008363),
            size: isSmallScreen ? 18 : 20,
          ),
          onPressed: () => _toggleKeyboardForField(fieldType),
          splashRadius: 20,
          padding: const EdgeInsets.all(4),
          constraints: const BoxConstraints.tightFor(width: 36, height: 36),
        ),
      ),
      style: TextStyle(fontSize: 13 * _fontScale),
      onSubmitted: onSubmitted,
      onTap: onTap,
      onChanged: onChanged,
      onTapOutside: (event) {
        // 关键修复：点击外部时更新键盘状态
        _hideKeyboardForField(fieldType);
        _unfocusField(fieldType);
      },
    );
  }

  // 输入框点击处理
  void _onInputTap(TextEditingController controller, String fieldType) {
    if (controller.text.isNotEmpty) {
      controller.selection = TextSelection(
        baseOffset: 0,
        extentOffset: controller.text.length,
      );
    }
    // 关键修复：点击输入框时仅聚焦不自动显示键盘
    _focusOnField(fieldType, showKeyboard: false);
  }

  // 重命名的焦点方法（处理包含Notes的场景）
  void _focusOnFieldWithNotes(String field, {required bool showKeyboard}) {
    FocusScope.of(context).unfocus();
    if (mounted) {
      switch (field) {
        case 'location':
          FocusScope.of(context).requestFocus(_locationFocusNode);
          break;
        case 'item':
          FocusScope.of(context).requestFocus(_itemFocusNode);
          break;
        case 'quantity':
          FocusScope.of(context).requestFocus(_quantityFocusNode);
          break;
        case 'destLoc':
          FocusScope.of(context).requestFocus(_destLocFocusNode);
          break;
        case 'notes':
          FocusScope.of(context).requestFocus(_notesFocusNode);
          break;
      }
      if (showKeyboard) {
        _showKeyboardForField(field);
      } else {
        _hideKeyboard();
        _updateKeyboardState(field, false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    final isSmallScreen = MediaQuery.of(context).size.width < 360;

    return Scaffold(
      appBar: AppBar(
        title: Text('Move', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18 * _fontScale)),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            _resetAllKeyboards();
            Navigator.pop(context);
          },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () {
              _resetAllKeyboards();
              Navigator.pushNamed(context, '/home');
            },
          ),
        ],
        backgroundColor: const Color(0xFF008363),
      ),
      resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          Positioned(
            top: 0,
            left: 0,
            right: 0,
            bottom: _bottomButtonHeight,
            child: GestureDetector(
              onTap: _resetAllKeyboards,
              behavior: HitTestBehavior.translucent,
              child: SingleChildScrollView(
                padding: EdgeInsets.all(isSmallScreen ? 16 : 32),
                child: Column(
                  children: [
                    _buildLabelInputRow(
                      label: 'Location:',
                      isRequired: true,
                      errorKey: 'location',
                      fieldType: 'location',
                    ),
                    const SizedBox(height: 20),
                    _buildLabelInputRow(
                      label: 'Item:',
                      isRequired: true,
                      errorKey: 'item',
                      fieldType: 'item',
                    ),
                    const SizedBox(height: 20),
                    _buildLabelInputRow(
                      label: 'Move Qty:',
                      isRequired: true,
                      errorKey: 'move quantity',
                      fieldType: 'quantity',
                      suffixWidget:currentQuantity != null? Text(
                        currentQuantity != null ? ' / $currentQuantity' : '',
                        style: TextStyle(fontSize: 13 * _fontScale),
                      ):null,
                    ),
                    const SizedBox(height: 50),
                    _buildLabelInputRow(
                      label: 'Dest Loc:',
                      isRequired: true,
                      errorKey: 'dest loc',
                      fieldType: 'destLoc',
                    ),
                    const SizedBox(height: 20),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        SizedBox(
                          width: 120,
                          child: Padding(
                            padding: const EdgeInsets.only(top: 8),
                            child: Text(
                              'Notes:',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 13 * _fontScale,
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: TextField(
                            focusNode: _notesFocusNode,
                            controller: _notesController,
                            maxLines: 6,
                            decoration: const InputDecoration(
                              hintText: 'Note...',
                              border: OutlineInputBorder(),
                              contentPadding: EdgeInsets.all(10),
                            ),
                            style: TextStyle(fontSize: 13 * _fontScale),
                            onTap: _resetAllKeyboards,
                            onTapOutside: (event) => _notesFocusNode.unfocus(),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 20),
                  ],
                ),
              ),
            ),
          ),
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: Container(
              padding: const EdgeInsets.all(24),
              color: Theme.of(context).scaffoldBackgroundColor,
              child: ElevatedButton(
                onPressed: _submitForm,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF008363),
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: Text(
                  'Submit',
                  style: TextStyle(
                    fontSize: 16 * _fontScale,
                    fontWeight: FontWeight.bold,
                    color: Colors.white
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}